package com.hctforgreen.greenservice.ui.adapter;

import java.io.File;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.provider.MediaStore;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hctforgreen.greenservice.R;
import com.hctforgreen.greenservice.SubmitFeedBackActivityV3;
import com.hctforgreen.greenservice.model.VideoEntity;
import com.hctforgreen.greenservice.ui.widget.GridViewIsChildOfScrollView;

public class SingleVideoListAdapter extends BaseAdapter implements
		OnItemClickListener {
	private Activity mActivity;
	private View mConvertView;
	private GridViewIsChildOfScrollView mGridView;

	/**
	 * 图片在SDCard的路径
	 */
	private List<VideoEntity> mEntities;

	private SubmitFeedBackActivityV3 mSelf;

	public SingleVideoListAdapter(GridViewIsChildOfScrollView gridView,
			Activity activity, View convertView, List<VideoEntity> entities,
			SubmitFeedBackActivityV3 self) {

		mGridView = gridView;
		mActivity = activity;
		mConvertView = convertView;
		mEntities = entities;
		mSelf = self;
		initVideoList();
		mGridView.setAdapter(this);
		mGridView.setOnItemClickListener(this);
	}

	private void initVideoList() {
		if (mEntities == null || mEntities.size() == 0) {
			VideoEntity entity = new VideoEntity();
			mEntities.add(entity);
		}
	}

	@Override
	public int getCount() {
		return mEntities.size();
	}

	@Override
	public Object getItem(int position) {
		return mEntities.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		ViewCache viewCache;
		final VideoEntity entity = (VideoEntity) getItem(position);
		if (convertView == null) {
			convertView = View.inflate(mActivity, R.layout.item_single_pic_lst,
					null);
			viewCache = new ViewCache(convertView);
			convertView.setTag(viewCache);
		} else {
			viewCache = (ViewCache) convertView.getTag();
		}
		if (!"".equals(entity.path)) {
			File file = new File(entity.path);
			Log.w("video_file", file.exists() + "");
			Bitmap bitmap = getVideoThumbnail(entity.path, 800, 800,
					MediaStore.Video.Thumbnails.MICRO_KIND);
			if (bitmap != null) {
				viewCache.getAddIv().setImageBitmap(bitmap);
				viewCache.getDeleteIv().setVisibility(View.VISIBLE);
				viewCache.getTvName().setText(file.getName());
				viewCache.getTvSize().setText(
						Formatter.formatFileSize(mActivity, file.length()));

			} else {
				Toast.makeText(
						mActivity,
						mActivity
								.getString(R.string.feedback_video_corrupt_reply),
						Toast.LENGTH_SHORT).show();
				entity.path = "";
				viewCache.getDeleteIv().setVisibility(View.GONE);
				viewCache.getTvName().setText("");
				viewCache.getTvSize().setText("");
			}

		} else if (entity.path.equals("")) {
			viewCache.getAddIv().setImageResource(R.drawable.add_pic_btn_u);
			viewCache.getDeleteIv().setVisibility(View.GONE);
			viewCache.getTvName().setText("");
			viewCache.getTvSize().setText("");
		}
		viewCache.getAddIv().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				add(entity, position);
			}
		});
		viewCache.getDeleteIv().setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				delete(entity, position);
			}
		});
		return convertView;
	}

	private void delete(VideoEntity entity, int position) {
		mEntities.clear();
		mEntities.add(new VideoEntity());
		notifyDataSetChanged();
	}

	/**
	 * 视频
	 */
	private void add(VideoEntity entity, int position) {
		mSelf.mPosition = position;
		try {
			String[] items = mActivity.getResources().getStringArray(
					R.array.feed_back_get_video);
			AlertDialog.Builder builder = new Builder(mActivity);
			builder.setTitle(
					mActivity.getString(R.string.feed_back_video_title))
					.setItems(items, new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							switch (which) {
							case 0:
								Intent intent = new Intent(
										MediaStore.ACTION_VIDEO_CAPTURE);
								intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,
										1);
								mActivity.startActivityForResult(intent,
										mSelf.VIDEO_PICKED_WITH_DATA);
								break;
							case 1:
								intent = getVideoPickIntent();
								mActivity.startActivityForResult(intent,
										mSelf.VIDEO_PICKED_WITH_DATA);
								break;
							default:
								break;
							}
						}
					}).create().show();

		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	// public static Intent getPhotoPickIntent() {
	//
	// Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
	// intent.setType("image/*");
	// return intent;
	// }

	public static Intent getVideoPickIntent() {

		//Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setType("video/*");
		return intent;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

	}

	/**
	 * 获取视频的缩略图 先通过ThumbnailUtils来创建一个视频的缩略图，然后再利用ThumbnailUtils来生成指定大小的缩略图。
	 * 如果想要的缩略图的宽和高都小于MICRO_KIND，则类型要使用MICRO_KIND作为kind的值，这样会节省内存。
	 * 
	 * @param videoPath
	 *            视频的路径
	 * @param width
	 *            指定输出视频缩略图的宽度
	 * @param height
	 *            指定输出视频缩略图的高度度
	 * @param kind
	 *            参照MediaStore.Images.Thumbnails类中的常量MINI_KIND和MICRO_KIND。
	 *            其中，MINI_KIND: 512 x 384，MICRO_KIND: 96 x 96
	 * @return 指定大小的视频缩略图
	 */
	private Bitmap getVideoThumbnail(String videoPath, int width, int height,
			int kind) {
		Bitmap bitmap = null;
		// 获取视频的缩略图
		bitmap = ThumbnailUtils.createVideoThumbnail(videoPath, kind);
		if (bitmap == null) {
			return null;
		}
		System.out.println("w" + bitmap.getWidth());
		System.out.println("h" + bitmap.getHeight());
		bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
				ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
		return bitmap;
	}

	class ViewCache {
		private View baseView;

		private ImageView addIv;
		private ImageView deleteIv;

		private TextView tvName;

		private TextView tvSize;

		public ViewCache(View view) {
			baseView = view;
		}

		public TextView getTvName() {
			if (tvName == null) {
				tvName = (TextView) baseView.findViewById(R.id.tv_video_name);
			}
			return tvName;
		}

		public TextView getTvSize() {
			if (tvSize == null) {
				tvSize = (TextView) baseView.findViewById(R.id.tv_video_length);
			}

			return tvSize;
		}

		public ImageView getAddIv() {
			if (addIv == null) {
				addIv = (ImageView) baseView.findViewById(R.id.iv_add);
			}
			return addIv;
		}

		public ImageView getDeleteIv() {
			if (deleteIv == null) {
				deleteIv = (ImageView) baseView.findViewById(R.id.iv_delete);
			}
			return deleteIv;
		}
	}
}
